import { createRouter, createWebHashHistory } from 'vue-router';
import { ERROR_403,ERROR_404 } from './consts';
import { useUserStore } from '/@/store/modules/user';
const modules = import.meta.glob('./modules/**/*.ts',{eager: true})
export const routeMenuList: any = []
Object.keys(modules).forEach(key=>{
    const module: any = modules[key]
    if(Array.isArray(module.default)) {
        routeMenuList.push(...module.default)
    } else {
        routeMenuList.push(module.default)
    }
})
// app router
export const router = createRouter({
    history: createWebHashHistory('/'),
    routes: [{
        path: '/login',
        name: 'login',
        meta: {
            title: '登录',
        },
        component: () =>{
            return import('/@/views/sys/login/index.vue')
        }
    },
    {
        path: '/error/403',
        name: 'error_403',
        meta: {
            title: '403'
        },
        component: ERROR_403
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'error_404',
        meta: {
            title: '404'
        },
        component: ERROR_404
    },
    ...routeMenuList,
]
});
router.beforeEach((to: any, from, next)=>{
    const userStore = useUserStore()
    if(to.name == 'login') {
        // 如果为登录页面
        if(userStore.getToken) {
            // 如果token存在，则跳转到首页
            next({
                path: '/'
            })
        } else {
            next()
        }
    } else {
        // 非登录页面
        if(userStore.getToken) {
            // 如果token存在
            if(userStore.hasPerm(to?.meta?.perm)) {
                next()
            } else {
                next({
                    name: 'error_403'
                })
            }
        } else {
            next({
                name: 'login'
            })
        }
    }
    
})